package com.wlw.admin.openeye.ui.activity

import android.annotation.TargetApi
import android.graphics.Typeface
import android.os.Build
import android.support.annotation.RequiresApi
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.transition.Fade
import android.transition.Transition
import android.transition.TransitionInflater
import android.view.View
import android.view.animation.AnimationUtils
import android.view.inputmethod.EditorInfo
import com.google.android.flexbox.*
import com.wlw.admin.openeye.MyApplication
import com.wlw.admin.openeye.R
import com.wlw.admin.openeye.base.BaseActivity
import com.wlw.admin.openeye.mvp.contract.SearchContract
import com.wlw.admin.openeye.mvp.model.bean.HomeBean
import com.wlw.admin.openeye.mvp.presenter.SearchPresenter
import com.wlw.admin.openeye.net.exception.ErrorStatus
import com.wlw.admin.openeye.showToast
import com.wlw.admin.openeye.ui.adapter.CategoryDetailAdapter
import com.wlw.admin.openeye.ui.adapter.HotKeywordsAdapter
import com.wlw.admin.openeye.utils.CleanLeakUtils
import com.wlw.admin.openeye.utils.StatusBarUtil
import com.wlw.admin.openeye.utils.ViewAnimUtils
import kotlinx.android.synthetic.main.activity_search.*

class SearchActivity : BaseActivity(), SearchContract.View {


    private val mPresenter by lazy {
        SearchPresenter()
    }
    private val mResultAdapter by lazy {
        CategoryDetailAdapter(this, itemList)
    }
    private val mHotKeywordsAdapter: HotKeywordsAdapter by lazy {
        HotKeywordsAdapter(this, flexList)
    }

    private var itemList = ArrayList<HomeBean.Issue.Item>()
    private var flexList = ArrayList<String>()

    private var mTextTypeface: Typeface? = null

    private var keyWords: String? = null

    private var loadingMore = false

    init {
        mPresenter.attachView(this)
        mTextTypeface = Typeface.createFromAsset(MyApplication.context.assets, "fonts/FZLanTingHeiS-L-GB-Regular.TTF")
    }

    override fun layoutId(): Int = R.layout.activity_search

    override fun initData() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setUpEnterAnimation()
            setUpExitAnimation()
        } else {
            setUpView()
        }

    }

    private fun setUpView() {
        val animation = AnimationUtils.loadAnimation(this, android.R.anim.fade_in)
        animation.duration = 300
        container.startAnimation(animation)
        container.visibility = View.VISIBLE
        openKeyBord(et_search_view, applicationContext)
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    private fun setUpExitAnimation() {
        val fade = Fade()
        window.returnTransition = fade
        fade.duration = 300
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    private fun setUpEnterAnimation() {
        val transition = TransitionInflater.from(this)
                .inflateTransition(R.transition.arc_motion)
        window.sharedElementEnterTransition = transition
        transition.addListener(object :Transition.TransitionListener{
            override fun onTransitionResume(p0: Transition?) {

            }

            override fun onTransitionPause(p0: Transition?) {
            }

            override fun onTransitionCancel(p0: Transition?) {
            }

            override fun onTransitionStart(p0: Transition?) {
            }

            override fun onTransitionEnd(p0: Transition?) {
                transition.removeListener(this)
                animateRevealShow()
            }

        })
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private fun animateRevealShow() {
        ViewAnimUtils.animateRevealShow(this,cl_frame,fab_circle.width/2,R.color.color_blue,object:ViewAnimUtils.OnRevealAnimationListener{
            override fun onRevealHide() {

            }

            override fun onRevealShow() {
                setUpView()
            }
        })

    }

    override fun initView() {
        tv_title_tip.typeface = mTextTypeface
        tv_hot_search_words.typeface = mTextTypeface
        //初始化查询结果的 RecyclerView
        mRecyclerView_result.layoutManager = LinearLayoutManager(this)
        mRecyclerView_result.adapter = mResultAdapter

        mRecyclerView_result.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                val itemCount = recyclerView.layoutManager?.itemCount
                val lastVisibleItem = (recyclerView.layoutManager as LinearLayoutManager).findLastVisibleItemPosition()
                if (!loadingMore && lastVisibleItem == (itemCount!! - 1)) {
                    loadingMore = true
                    mPresenter.loadMoreData()
                }
            }
        })

        tv_cancel.setOnClickListener { onBackPressed() }
        et_search_view.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                closeSoftKeyboard()
                keyWords = et_search_view.text.toString().trim()
                if (keyWords.isNullOrEmpty()) {
                    showToast("请输入你感兴趣的关键词")
                } else {
                    mPresenter.querySearchData(keyWords!!)
                }
            }
            false
        }
        mLayoutStatusView = multipleStatusView
        StatusBarUtil.darkMode(this)
        StatusBarUtil.setPaddingSmart(this, toolbar)
    }

    override fun start() {
        mPresenter.requestHotWordData()
    }

    override fun setHotWordData(string: ArrayList<String>) {
        showHotWordView()
        flexList.clear()
        flexList.addAll(string)
        mHotKeywordsAdapter.notifyDataSetChanged()
        val flexLayoutManager = FlexboxLayoutManager(this)
        flexLayoutManager.flexWrap = FlexWrap.WRAP //按正常方向换行
        flexLayoutManager.flexDirection = FlexDirection.ROW//主轴为水平方向，起点在左端
        flexLayoutManager.alignItems = AlignItems.CENTER //定义项目在副轴轴上如何对齐
        flexLayoutManager.justifyContent = JustifyContent.FLEX_START

        mRecyclerView_hot.layoutManager = flexLayoutManager
        mRecyclerView_hot.adapter = mHotKeywordsAdapter
        mHotKeywordsAdapter.setOnTagItemClickListener {
            closeSoftKeyboard()
            keyWords = it
            mPresenter.querySearchData(it)
        }

    }

    override fun setSearchResult(issue: HomeBean.Issue) {
        hideHotWordView()
        tv_search_count.visibility = View.VISIBLE
        tv_search_count.text = String.format(resources.getString(R.string.search_result_count), keyWords, issue.total)
        itemList = issue.itemList
        mResultAdapter.addData(itemList)
        loadingMore = false
    }

    private fun showHotWordView() {
        layout_hot_words.visibility = View.VISIBLE
        layout_content_result.visibility = View.GONE

    }

    private fun hideHotWordView() {
        layout_hot_words.visibility = View.GONE
        layout_content_result.visibility = View.VISIBLE

    }

    override fun closeSoftKeyboard() {
        closeKeyBord(et_search_view, this)
    }

    override fun setEmptyView() {
        showToast("抱歉，没有找到相匹配的内容")
        hideHotWordView()
        tv_search_count.visibility = View.GONE
        mLayoutStatusView?.showEmpty()

    }

    override fun showError(errorMsg: String, errorCode: Int) {
        showToast(errorMsg)
        if (errorCode == ErrorStatus.NETWORK_ERROR) {
            mLayoutStatusView?.showNoNetwork()
        } else {
            mLayoutStatusView?.showError()
        }
    }

    override fun showLoading() {
        mLayoutStatusView?.showContent()
    }

    override fun dismissLoading() {
    }

    override fun onBackPressed() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ViewAnimUtils.animateRevealHide(this, cl_frame, fab_circle.width / 2, R.color.backgroundColor, object : ViewAnimUtils.OnRevealAnimationListener {
                override fun onRevealShow() {

                }

                override fun onRevealHide() {
                    defaultBackPressed()
                }
            })
        } else {
            defaultBackPressed()
        }
    }

    private fun defaultBackPressed() {
        closeSoftKeyboard()
        super.onBackPressed()
    }

    override fun onDestroy() {
        CleanLeakUtils.fixInputMethodManagerLeak(this)
        super.onDestroy()
        mPresenter.detachView()
        mTextTypeface = null
    }
}
